//
//  YKMineViewController.m
//  AutocCarApp
//
//  Created by dllo on 15/11/17.
//  Copyright © 2015年 尹凯. All rights reserved.
//

#import "MineViewController.h"
#import "YKLoadingViewController.h"
#import "CollectionViewController.h"

@interface MineViewController ()<UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (nonatomic, retain)UIView *headView;
@property (nonatomic, retain)UILabel *upLabel;
@property (nonatomic, retain)UIView *notLoad;
@property (nonatomic, retain)UIView *myView;
@property (nonatomic, retain)UIView *load;
@property (nonatomic, retain)UIAlertView *myAlertView;

@property (nonatomic, retain)MBProgressHUD *HUD;

@property (nonatomic, retain)UIImageView *headImageView;
@property (nonatomic, retain)UILabel *userNameLabel;

@end

@implementation MineViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:0.8];
    self.headView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 280, 44)];
    [self.navigationController.navigationBar addSubview:self.headView];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(22, 0, 34, 45)];
    label.textColor = [UIColor blueColor];
    label.text = @"我";
    label.font = [UIFont systemFontOfSize:18];
    [self.headView addSubview:label];
    
    UIView *sliderView = [[UIView alloc] initWithFrame:CGRectMake(17, 42, 25, 2)];
    sliderView.backgroundColor = [UIColor blueColor];
    [self.headView addSubview:sliderView];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@""] style:UIBarButtonItemStyleDone target:self action:@selector(rightBarButtonItemAct:)];
    
    self.myView = [[UIView alloc] initWithFrame:CGRectMake(0, 10, Width, 220)];
    self.myView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.myView];
    
    
    self.load = [[UIView alloc] initWithFrame:CGRectMake(0, 0, Width, 220)];
    self.load.backgroundColor = [UIColor whiteColor];
    [self.myView addSubview:self.load];
    
    self.headImageView = [[UIImageView alloc] initWithFrame:CGRectMake(30, 25, 100, 100)];
    self.headImageView.image = [UIImage imageNamed:@"authorhead@2x.png"];
    
    //裁掉边框
    self.headImageView.layer.masksToBounds = YES;
    //设置半径
    self.headImageView.layer.cornerRadius = 50;
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];
    [tap addTarget:self action:@selector(tapAction:)];
    self.headImageView.userInteractionEnabled = YES;
    [self.headImageView addGestureRecognizer:tap];
    
    [self.load addSubview:self.headImageView];
    
    self.userNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(150, 30, 150, 30)];
    self.userNameLabel.backgroundColor = [UIColor greenColor];
    self.userNameLabel.textColor = [UIColor lightGrayColor];
    [self.load addSubview:self.userNameLabel];
    
    UIButton *zhuxiao = [UIButton buttonWithType:UIButtonTypeSystem];
    zhuxiao.frame = CGRectMake(150, 180, 75, 30);
    zhuxiao.backgroundColor = [UIColor redColor];
    [zhuxiao setTitle:@"注销" forState:UIControlStateNormal];
    [zhuxiao setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    zhuxiao.tag = 1003;
    [zhuxiao addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.load addSubview:zhuxiao];
    
    
    self.notLoad = [[UIView alloc] initWithFrame:CGRectMake(0, 0, Width, 220)];
    self.notLoad.backgroundColor = [UIColor whiteColor];
    [self.myView addSubview:self.notLoad];
    
    UILabel *tempLabel = [[UILabel alloc] initWithFrame:CGRectMake(100, 40, 20, 20)];
    tempLabel.text = @"立即登录，更多体验";
    tempLabel.font = [UIFont systemFontOfSize:20];
    [tempLabel sizeToFit];
    [self.notLoad addSubview:tempLabel];
    
    NSArray *array = [NSArray arrayWithObjects:@"me_person@2x.png", @"me_qq@2x.png", @"me_weibo@2x.png", nil];
    NSArray *titles = [NSArray arrayWithObjects:@"账号登陆", @"QQ登录", @"微博登陆", nil];
    for (int i = 0; i < 3; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(i * Width / 3, 120, Width / 3, 100);
        [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
        button.tag = 1000 + i;
        
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(40, 20, 40, 40)];
        imageView.image = [UIImage imageNamed:[array objectAtIndex:i]];
        [button addSubview:imageView];
        
        UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(35, 60, 60, 20)];
        title.font = [UIFont systemFontOfSize:14];
        title.text = [titles objectAtIndex:i];
        [title sizeToFit];
        [button addSubview:title];
        
        [self.notLoad addSubview:button];
        
    }
    
    UIImageView *imageView1 = [[UIImageView alloc] initWithFrame:CGRectMake(Width / 3 - 1, 140, 2, 70)];
    imageView1.image = [UIImage imageNamed:@"sideBar_shadow_bg@2x.png"];
    [self.notLoad addSubview:imageView1];
    
    UIImageView *imageView2 = [[UIImageView alloc] initWithFrame:CGRectMake(Width / 3 * 2 - 1, 140, 2, 70)];
    imageView2.image = [UIImage imageNamed:@"sideBar_shadow_bg@2x.png"];
    [self.notLoad addSubview:imageView2];

    
    UIView *downView = [[UIView alloc] initWithFrame:CGRectMake(0, 245, Width, 280)];
    downView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:downView];
    
    NSArray *otherTitles = [NSArray arrayWithObjects:@"我的收藏", @"浏览历史", @"草稿箱", @"清除缓存", nil];
    NSArray *images = [NSArray arrayWithObjects:@"me_favourite@2x.png", @"icon_history@3x.png", @"me_draft@2x.png", @"me_setting@2x.png", nil];
    for (int i = 0; i < images.count; i++) {
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 70 * i, Width, 70)];
        button.tag = 10000 + i;
        [button addTarget:self action:@selector(downButtonAct:) forControlEvents:UIControlEventTouchUpInside];
        
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(15, 20, 30, 30)];
        NSString *image = [images objectAtIndex:i];
        imageView.image = [UIImage imageNamed:image];
        [button addSubview:imageView];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(75, 20, 150, 30)];
        NSString *title = [otherTitles objectAtIndex:i];
        label.text = title;
        label.font = [UIFont systemFontOfSize:20];
        [button addSubview:label];
        
        [downView addSubview:button];
    }
    
    UIImageView *imageView3 = [[UIImageView alloc] initWithFrame:CGRectMake(50, 69, 325, 1)];
    imageView3.image = [UIImage imageNamed:@"spring_line@2x.png"];
    [downView addSubview:imageView3];
    
    UIImageView *imageView4 = [[UIImageView alloc] initWithFrame:CGRectMake(50, 139, 325, 1)];
    imageView4.image = [UIImage imageNamed:@"spring_line@2x.png"];
    [downView addSubview:imageView4];
    
    UIImageView *imageView5 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 209, Width, 1)];
    imageView5.image = [UIImage imageNamed:@"spring_line@2x.png"];
    [downView addSubview:imageView5];

}

- (void)tapAction:(UITapGestureRecognizer *)tap{
    [self presentToViewController];
}

- (void)presentToViewController{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.allowsEditing = YES;
    picker.delegate = self;
    [self presentViewController:picker animated:YES completion:^{
        
        
    }];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    UIImage *image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    self.headImageView.image = image;
    
    NSString *document = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    
    //将一个字典写入到本地
    NSString *string = [NSString stringWithFormat:@"/%@.plist", self.userNameLabel.text];
    NSString *dicPath = [document stringByAppendingString:string];
    //字面量:针对不可变数组,字典
    //@()通常是将基本数据类型转成对象类型,相当于NSMumber
    
    NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
    [dictionary setObject:UIImagePNGRepresentation(image) forKey:@"image"];
    
    BOOL result = [dictionary writeToFile:dicPath atomically:YES];
    if (result) {
        NSLog(@"写入成功");
    }
    else{
        NSLog(@"写入失败");
    }
    
    [picker dismissViewControllerAnimated:YES completion:^{
        
        
    }];
}


- (void)buttonAction:(UIButton *)button{
    if (button.tag == 1000) {
        NSLog(@"555555");
        
        YKLoadingViewController *loadingVC = [[YKLoadingViewController alloc] init];
        UINavigationController *navC = [[UINavigationController alloc] initWithRootViewController:loadingVC];
        [self presentViewController:navC animated:YES completion:^{
            
            
        }];
    }
    if (button.tag == 1003) {
        self.myAlertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"是否注销" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [self.myAlertView show];
    }
}

- (void)downButtonAct:(UIButton *)button{
    if (button.tag == 10000) {
        CollectionViewController *collectionVC = [[CollectionViewController alloc] init];
        
        UINavigationController *navC = [[UINavigationController alloc] initWithRootViewController:collectionVC];
        
        [self presentViewController:navC animated:YES completion:^{
            
            
        }];
    }
//    if (button.tag == 10001) {
//        YKHistoryViewController *historyVC = [[YKHistoryViewController alloc] init];
//        UINavigationController *navC = [[UINavigationController alloc] initWithRootViewController:historyVC];
//        historyVC
//    }
    if (button.tag == 10003) {
        NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
        NSLog(@"哈哈哈哈哈 ===== %@", path);
        NSString *messageStr = [NSString stringWithFormat:@"缓存大小为: %.1fM, 需要清除缓存么?", [self folderSizeAtPath:path]];
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:messageStr delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alertView show];
    }
}

// 根据根据点击按钮的索引处理点击事件
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (alertView == _myAlertView) {
        if (buttonIndex == 1) {
            [self.myView bringSubviewToFront:self.notLoad];
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"isLogin"];
        }
    }
    else {
        if (buttonIndex == 0) {
        }
        if (buttonIndex == 1) {
            NSLog(@"VVVVVVVVVVVVV");
            NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
            [self clearCache:path];
            [self clearSuccess];
        }
    }
}

-(void)clearSuccess{
    self.HUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
    [self.navigationController.view addSubview:self.HUD];
    //显示的文字
    self.HUD.labelText = @"删除成功    ";
    //是否有遮罩
    self.HUD.dimBackground = NO;
    self.HUD.labelFont = [UIFont boldSystemFontOfSize:22];
    self.HUD.backgroundColor = [UIColor clearColor];
    //提示框的样式
    self.HUD.mode = MBProgressHUDModeCustomView;
    [self.HUD show:YES];
    //两秒之后隐藏
    [self.HUD hide:YES afterDelay:0.5];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated{
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"isNight"] == nil) {
        self.navigationItem.rightBarButtonItem.image = [UIImage imageNamed:@""];
    }
    else {
        self.navigationItem.rightBarButtonItem.image = [UIImage imageNamed:@""];
    }
    
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"isLogin"] == nil) {
        
    }
    else{
        NSString *name = [[NSUserDefaults standardUserDefaults] objectForKey:@"isLogin"];
        self.userNameLabel.text = name;
        
        NSString *document = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        
        //将一个字典写入到本地
        NSString *string = [NSString stringWithFormat:@"/%@.plist", self.userNameLabel.text];
        NSString *dicPath = [document stringByAppendingString:string];
        if ([[NSFileManager defaultManager] fileExistsAtPath:dicPath]) {
            NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithContentsOfFile:dicPath];
            NSData* imageData = [dictionary objectForKey:@"image"];
            UIImage* image = [UIImage imageWithData:imageData];
            self.headImageView.image = image;
            [self.myView bringSubviewToFront:self.load];
            return;
        }
        
        self.headImageView.image = [UIImage imageNamed:@"authorhead@2x.png"];
        [self.myView bringSubviewToFront:self.load];
    }
}


#pragma mark - 夜间模式按钮逻辑
- (void)rightBarButtonItemAct:(UIBarButtonItem *)barButtonItem{
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"isNight"] == nil) {
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"me_day@2x.png"] style:UIBarButtonItemStyleDone target:self action:@selector(rightBarButtonItemAct:)];
        [[NSUserDefaults standardUserDefaults] setValue:@"1" forKey:@"isNight"];
    }
    else {
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"me_moon@2x.png"] style:UIBarButtonItemStyleDone target:self action:@selector(rightBarButtonItemAct:)];
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"isNight"];
    }
}

#pragma mark - 删除缓存方法
//文件大小
- (long long)fileSizeAtPath:(NSString*)filePath{
    
    NSFileManager* manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]){
        
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}

/*整个目录的文件大小*/
- (float)folderSizeAtPath:(NSString *) folderPath{
    
    NSFileManager* manager = [NSFileManager defaultManager];
    
    if (![manager fileExistsAtPath:folderPath]) return 0;
    
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    NSString* fileName;
    long long folderSize = 0;
    
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        
        NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
    }
    return folderSize/(1024.0*1024.0);
}

- (void)clearCache:(NSString *)path{
    NSFileManager *fileManager=[NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:path]) {
        NSArray *childerFiles=[fileManager subpathsAtPath:path];
        for (NSString *fileName in childerFiles) {
            //如有需要，加入条件，过滤掉不想删除的文件
            NSString *absolutePath=[path stringByAppendingPathComponent:fileName];
            [fileManager removeItemAtPath:absolutePath error:nil];
        }
    }
    [[SDImageCache sharedImageCache] cleanDisk];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
